package com.qf.redis.service.impl;

import com.alibaba.fastjson.JSON;
import com.qf.redis.entity.User;
import com.qf.redis.service.IUserService;
import com.qf.redis.utils.IDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    // 用户数据可以保存在hash结构中
    // hash结构: key (filed value)value
    // user: id  JSON
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IDUtils idUtils;

    private String key = "redis:user";

    @Override
    public Boolean save(User user) {

        // 1.先获取一个user的Id
        Long id = idUtils.getId();

        // 2.给对象设置ID
        user.setId(id);

        // 3.把对象保存在Redis中,把对象转成JSON字符串保存在redis中
        stringRedisTemplate.opsForHash().put(key, id.toString(), JSON.toJSONString(user));
        return true;
    }

    @Override
    public Boolean updateById(User user) {
        // 更新其实就是覆盖
        stringRedisTemplate.opsForHash().put(key, user.getId().toString(), JSON.toJSONString(user));
        return true;
    }

    @Override
    public User info(Integer id) {
        // 从Redis中查询出来的都是JSON字符串
        String json = (String) stringRedisTemplate.opsForHash().get(key, id.toString());
        return JSON.parseObject(json, User.class);
    }

    @Override
    public Boolean removeById(Integer id) {
        return stringRedisTemplate.opsForHash().delete(key, id.toString()) > 0;
    }

    @Override
    public List<User> listUser() {
        List<User> users = new ArrayList<>();
        List<Object> values = stringRedisTemplate.opsForHash().values(key);
        for (Object value : values) {
            // 把JSON字符串转成User对象，
            User user = JSON.parseObject(value.toString(), User.class);
            // 然后添加到集合中
            users.add(user);
        }
        return users;
    }
}
